import api from '@/api';

// 消息相关的store模块
const message = {
  namespaced: true,
  
  state: {
    messages: [],           // 消息列表
    loading: false,         // 加载状态
    unreadCount: 0,         // 未读消息数量
    total: 0,               // 消息总数
    params: {},              // 当前查询参数
    categoryCounts: {}       // 各分类消息数量
  },
  
  mutations: {
    SET_MESSAGES(state, messages) {
      state.messages = messages;
    },
    SET_LOADING(state, status) {
      state.loading = status;
    },
    SET_UNREAD_COUNT(state, count) {
      state.unreadCount = count;
    },
    SET_TOTAL(state, total) {
      state.total = total;
    },
    SET_PARAMS(state, params) {
      state.params = params;
    },
    SET_CATEGORY_COUNTS(state, counts) {
      state.categoryCounts = counts;
    }
  },
  
  actions: {
    // 获取消息
    // eslint-disable-next-line no-unused-vars
    async getMessages({ commit, state }, params) {
      commit('SET_LOADING', true);
      try {
        // 保存当前查询参数
        commit('SET_PARAMS', params);
        
        const response = await api.message.getList(params);
        
        if (response && (response.code === 0 || response.success)) {
          let messageList = [];
          let totalCount = 0;
          
          // 处理返回的消息列表数据
          if (Array.isArray(response.data)) {
            // 直接使用数组
            messageList = response.data;
            totalCount = response.total || messageList.length;
          } else if (response.data && Array.isArray(response.data.list)) {
            // 使用data.list数组
            messageList = response.data.list;
            totalCount = response.data.total || response.total || messageList.length;
          } else if (response.list && Array.isArray(response.list)) {
            // 使用response.list数组
            messageList = response.list;
            totalCount = response.total || messageList.length;
          } else if (response.data && !Array.isArray(response.data)) {
            // 单个对象转为数组
            messageList = [response.data];
            totalCount = 1;
          }
          
          // 确保消息总数至少为0
          totalCount = Math.max(totalCount || 0, 0);
          
          commit('SET_MESSAGES', messageList);
          commit('SET_TOTAL', totalCount);
          
          return {
            messages: messageList,
            total: totalCount,
            success: true
          };
        } else {
          commit('SET_MESSAGES', []);
          commit('SET_TOTAL', 0);
          
          return {
            messages: [],
            total: 0,
            success: false,
            error: response?.message || '获取消息失败'
          };
        }
      } catch (error) {
        commit('SET_MESSAGES', []);
        commit('SET_TOTAL', 0);
        
        return {
          messages: [],
          total: 0,
          success: false,
          error: error?.message || '获取消息列表失败'
        };
      } finally {
        commit('SET_LOADING', false);
      }
    },
    
    // 获取未读消息数量
    async fetchUnreadMessageCount({ commit, state }) {
      try {
        // 先尝试从API获取未读消息数量
        const response = await api.message.getUnreadCount();
        
        if (response && response.success) {
          const count = response.data || 0;
          commit('SET_UNREAD_COUNT', count);
          return count;
        } else {
          // 如果API未返回未读数量，尝试从当前消息列表计算
          if (state.messages && state.messages.length > 0) {
            // state: 0表示未读, state: 1表示已读
            const unreadCount = state.messages.filter(msg => msg.state === 0).length;
            commit('SET_UNREAD_COUNT', unreadCount);
            return unreadCount;
          }
          
          commit('SET_UNREAD_COUNT', 0);
          return 0;
        }
      } catch (error) {
        commit('SET_UNREAD_COUNT', 0);
        return 0;
      }
    },
    
    // 获取未读消息数量（兼容旧API名称）
    async getUnreadCount(context) {
      // 调用现有实现
      return context.dispatch('fetchUnreadMessageCount');
    },
    
    // 删除消息
    async deleteMessage({ commit, state, dispatch }, id) {
      try {
        // 从本地状态移除消息
        const messages = state.messages.filter(msg => msg.id !== id);
        commit('SET_MESSAGES', messages);
        
        // 如果删除的是未读消息，更新未读数量
        const deletedMsg = state.messages.find(msg => msg.id === id);
        if (deletedMsg && !deletedMsg.hasRead) {
          const unreadCount = state.unreadCount > 0 ? state.unreadCount - 1 : 0;
          commit('SET_UNREAD_COUNT', unreadCount);
        }
        
        // 更新总数
        if (state.total > 0) {
          commit('SET_TOTAL', state.total - 1);
        }
        
        // 发送API请求删除消息
        const response = await api.message.delete(id);
        
        if (response && response.success) {
          // 异步获取最新的未读消息数量
          dispatch('fetchUnreadMessageCount');
          
          return true;
        } else {
          // 恢复原始状态
          await dispatch('getMessages', state.params);
          return false;
        }
      } catch (error) {
        return false;
      }
    },
    
    // 标记消息为已读
    async markAsRead({ commit, state, dispatch }, id) {
      try {
        // 先在本地状态更新消息
        const messages = [...state.messages];
        const index = messages.findIndex(msg => msg.id === id);
        
        if (index !== -1) {
          // 更新状态
          messages[index] = { ...messages[index], hasRead: true };
          commit('SET_MESSAGES', messages);
          
          // 更新未读消息数
          if (state.unreadCount > 0) {
            commit('SET_UNREAD_COUNT', state.unreadCount - 1);
          }
        }
        
        // 发送API请求
        const response = await api.message.markAsRead(id);
        
        if (response && response.success) {
          // 异步获取最新的未读消息数量
          dispatch('fetchUnreadMessageCount');
          
          return true;
        } else {
          // 恢复原始状态
          await dispatch('getMessages', state.params);
          return false;
        }
      } catch (error) {
        return false;
      }
    },
    
    // 标记全部消息为已读
    async markAllAsRead({ commit, state, dispatch }) {
      try {
        // 先在本地状态更新消息
        const messages = state.messages.map(msg => {
          if (!msg.hasRead) {
            return { ...msg, hasRead: true };
          }
          return msg;
        });
        
        commit('SET_MESSAGES', messages);
        
        // 所有消息已读，未读数量为0
        commit('SET_UNREAD_COUNT', 0);
        
        // 发送API请求
        const response = await api.message.markAllAsRead();
        
        if (response && response.success) {
          // 刷新消息列表
          await dispatch('getMessages', state.params);
          
          return true;
        } else {
          // 恢复原始状态
          await dispatch('getMessages', state.params);
          return false;
        }
      } catch (error) {
        return false;
      }
    },
    
    // 获取消息分类计数
    async getCategoryCounts({ commit, dispatch }) {
      commit('SET_LOADING', true);
      try {
        const response = await api.message.getCategoryCounts();
        
        if (response && (response.code === 0 || response.success)) {
          let counts = {};
          
          // 处理返回数据
          if (response.data && typeof response.data === 'object') {
            counts = response.data;
          } else {
            // 如果后端返回数据结构不符合预期，使用默认值
            counts = {
              all: response.total || 0,
              unread: 0,
              private: 0,
              system: 0,
              comment: 0,
              like: 0
            };
          }
          
          commit('SET_CATEGORY_COUNTS', counts);
          return counts;
        }
        
        return {};
      } catch (error) {
        // 后端接口报错时，使用备用方案获取数据
        try {
          // 创建结果对象
          const counts = {
            all: 0,
            unread: 0,
            private: 0,
            system: 0, 
            comment: 0,
            like: 0
          };
          
          // 获取全部消息总数
          const allResponse = await api.message.getList({ count: true });
          if (allResponse && (allResponse.code === 0 || allResponse.success)) {
            counts.all = allResponse.total || 0;
          }
          
          // 获取未读消息数量
          const unreadCount = await dispatch('fetchUnreadMessageCount');
          counts.unread = unreadCount || 0;
          
          commit('SET_CATEGORY_COUNTS', counts);
          return counts;
        } catch (backupError) {
          return {};
        }
      } finally {
        commit('SET_LOADING', false);
      }
    }
  }
};

export default message; 